############################################################################
# 
# Cache (sqlite)
#
# Copyright (c) 2013, Alexander Galanin <al@galanin.nnov.ru>
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# * Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# * Neither the name of Alexander Galanin nor the names of its contributors
#   may be used to endorse or promote products derived from this software
#   without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL Alexander Galanin BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
############################################################################

package require Tcl 8.5
package require sqlite3
package require struct::set

package provide cache 1.0

namespace eval cache {

namespace export \
    init \
    keep \
    get \
    exists \
    keepCookie \
    getCookie \
    cleanup \
    destroy
namespace ensemble create

variable version 1

# Open or create new database
proc init {dbfile} {
    variable version

    if {[file exists $dbfile]} {
        sqlite3 db $dbfile
    } else {
        sqlite3 db $dbfile
        create
    }

    # getting database version
    set dbVersion [db eval {
        select
            version
        from
            version
    }]
    if {![string is integer -strict $dbVersion] || $dbVersion != $version} {
        puts stderr "cache: database version mismatch. Re-creating..."
        db close
        file delete $dbfile
        sqlite3 db $dbfile
        create
    }
}

# create tables and insert version data
proc create {} {
    variable version

    db eval {
        create table version (
            version integer not null
        )
    }
    db eval {
        insert into
            version
        values (
            $version
        )
    }
    db eval {
        create table cache (
            url text not null,
            key text not null,
            value text not null,
            datetime integer not null,
            primary key (url, key)
        )
    }
}

# Close database
proc destroy {} {
    db close
}

# Save key-value pairs into cache
proc keep {url args} {
    set datetime [clock seconds]
    dict for {key value} $args {
        db eval {
            insert or replace
                into cache
            values (
                $url,
                $key,
                $value,
                $datetime
            )
        }
    }
}

# Get value from cache. Empty value indicates NULL.
proc get {url} {
    db eval {
        select
            key,
            value
        from
            cache t
        where
            t.url = $url
    }
}

# Check that specified keys exists in the cache
proc exists {url keys} {
    set dbKeys [db eval {
        select
            key
        from
            cache
        where
            url = $url
    }]
    struct::set subsetof $keys $dbKeys
}

# Clean up cache items older than specified number of seconds
proc cleanup {offset} {
    set datetime [expr {[clock seconds] - $offset}]
    db eval {
        delete from
            cache
        where
            datetime < $datetime
    }
    db eval vacuum
    db eval reindex
}

}
